<template>
	<my-page title="联系记录" :is-back="true" :is-tabbar="false">
		<!-- 联系记录列表 -->
		<view v-if="contactList.length > 0">
			<view v-for="(group, groupIndex) in groupedContacts" :key="groupIndex">
				<!-- 日期分割线 -->
				<view class="date-divider">
					<text class="date-text">{{group.date}}</text>
				</view>
				
				<!-- 当日联系记录列表 -->
				<view class="contact-list">
					<view 
						class="contact-item" 
						v-for="(item, index) in group.items" 
						:key="index"
						@click="goToDetail(item)"
					>
						<image class="contact-img" :src="getImageUrl(item.imageUrl)" mode="aspectFill"></image>
						<view class="contact-info">
							<view class="contact-name">{{item.name}}</view>
							<view class="contact-time">{{item.time}}</view>
							<view class="contact-phone-box">
								<view class="contact-phone">{{item.phone}}</view>
								<view class="call-btn" @click.stop="makeCall(item.phone)">
									<text class="iconfont icon-tel"></text>
									<text>拨打</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view v-else class="empty-state">
			<text class="empty-text">暂无联系记录</text>
		</view>
		
		<!-- 清空历史按钮 -->
		<view class="clear-btn" v-if="contactList.length > 0" @click="clearHistory">
			<text class="clear-text">清空联系记录</text>
		</view>
	</my-page>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import MyPage from '@/components/MyPage.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 联系记录列表
const contactList = ref([])

// 按日期分组的联系记录
const groupedContacts = computed(() => {
	// 按日期分组
	const groups = {}
	
	contactList.value.forEach(item => {
		if (!groups[item.date]) {
			groups[item.date] = []
		}
		groups[item.date].push(item)
	})
	
	// 转换为数组格式
	const result = []
	for (const date in groups) {
		result.push({
			date: date,
			items: groups[date]
		})
	}
	
	// 按日期排序（最新日期在前）
	result.sort((a, b) => {
		const dateA = new Date(a.date)
		const dateB = new Date(b.date)
		return dateB - dateA
	})
	
	return result
})

// 获取联系历史
const getContactHistory = () => {
	try {
		const history = uni.getStorageSync('assetContactHistory')
		if (history) {
			contactList.value = JSON.parse(history)
		} else {
			contactList.value = []
		}
	} catch (e) {
		console.error('获取联系历史失败', e)
		contactList.value = []
	}
}

// 清空历史记录
const clearHistory = () => {
	uni.showModal({
		title: '提示',
		content: '确定要清空所有联系记录吗？',
		success: (res) => {
			if (res.confirm) {
				try {
					uni.removeStorageSync('assetContactHistory')
					contactList.value = []
					uni.showToast({
						title: '联系记录已清空',
						icon: 'success'
					})
				} catch (e) {
					console.error('清空联系记录失败', e)
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 处理图片URL
const getImageUrl = (imageUrl) => {
	// 处理null、undefined或空字符串的情况
	if (!imageUrl) return '/static/images/suoluetu.png'
	
	// 确保imageUrl是字符串类型
	if (typeof imageUrl !== 'string') {
		return '/static/images/suoluetu.png'
	}
	
	try {
		// 分割图片URL，取第一个
		const firstImage = imageUrl.split(',')[0]
		
		// 检查是否已包含http
		if (firstImage.startsWith('http')) {
			return firstImage
		}
		
		// 拼接基础URL
		return import.meta.env.VITE_APP_BASE_API + firstImage
	} catch (error) {
		console.error('处理图片URL出错:', error)
		return '/static/images/suoluetu.png'
	}
}

// 拨打电话
const makeCall = (phone) => {
	if (!phone) {
		uni.showToast({
			title: '无效的电话号码',
			icon: 'none'
		})
		return
	}
	
	uni.makePhoneCall({
		phoneNumber: phone,
		fail: () => {
			uni.showToast({
				title: '拨打电话失败',
				icon: 'none'
			})
		}
	})
}

// 跳转详情页
const goToDetail = (item) => {
	uni.navigateTo({
		url: `/pages/asset/detail?id=${item.id}`
	})
}

// 在页面加载时获取数据
onMounted(() => {
	getContactHistory()
})

// 页面显示时刷新联系记录
onShow(() => {
	getContactHistory()
})
</script>

<style lang="scss" scoped>
@import '@/static/styles/index.scss';

::v-deep .my_page {
	.my_header {
		background: linear-gradient(to right, #2979ff, #1565C0);
		.wrap {
			background: linear-gradient(to right, #2979ff, #1565C0);
		}
	}
}

// 日期分割线
.date-divider {
	padding: 20rpx 30rpx 10rpx;
	background-color: #f5f5f5;
	
	.date-text {
		font-size: 28rpx;
		color: #666;
		font-weight: bold;
	}
}

// 联系记录列表样式
.contact-list {
	padding: 0 30rpx;
	
	.contact-item {
		display: flex;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		
		.contact-img {
			width: 220rpx;
			height: 160rpx;
			border-radius: 8rpx;
			margin: 20rpx;
		}
		
		.contact-info {
			flex: 1;
			padding: 20rpx 20rpx 20rpx 0;
			
			.contact-name {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 10rpx;
				font-weight: bold;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
			
			.contact-time {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 20rpx;
			}
			
			.contact-phone-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.contact-phone {
					font-size: 30rpx;
					color: #666;
					font-weight: bold;
				}
				
				.call-btn {
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #2979ff;
					color: #fff;
					padding: 8rpx 20rpx;
					border-radius: 30rpx;
					font-size: 24rpx;
					
					.iconfont {
						margin-right: 6rpx;
						font-size: 24rpx;
					}
				}
			}
		}
	}
}

// 空状态样式
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	
	.empty-text {
		font-size: 30rpx;
		color: #999;
	}
}

// 清空按钮样式
.clear-btn {
	margin: 30rpx;
	padding: 20rpx 0;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	text-align: center;
	
	.clear-text {
		font-size: 30rpx;
		color: #666;
	}
}
</style>
